package com.cyx.nutz;

import org.apache.velocity.app.Velocity;
import org.nutz.dao.Chain;
import org.nutz.dao.Cnd;
import org.nutz.dao.Dao;
import org.nutz.dao.Sqls;
import org.nutz.dao.impl.FileSqlManager;
import org.nutz.dao.sql.Sql;
import org.nutz.dao.util.Daos;
import org.nutz.ioc.Ioc;
import org.nutz.lang.Strings;
import org.nutz.log.Log;
import org.nutz.log.Logs;
import org.nutz.mvc.NutConfig;
import org.nutz.mvc.Setup;

import javax.servlet.ServletContext;
import java.io.IOException;
import java.util.*;

public class MainSetup implements  Setup{
    private static final Log log = Logs.get();
    @Override
    public void init(NutConfig config) {
        try {
            Ioc ioc = config.getIoc();
            Dao dao = ioc.get(Dao.class);
            //初始化数据表
            initSysData(config, dao);
            //初始化Velocity
            velocityInit(config);

            //初始化系统变量
            initSysSetting(config, dao);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void destroy(NutConfig nutConfig) {

    }

    /**
     * 初始化数据库
     *
     * @param config
     * @param dao
     */
    private void initSysData(NutConfig config, Dao dao) {
        Daos.createTablesInPackage(dao, "com.cyx.nutz", true);

    }

    /**
     * 初始化系统变量
     *
     * @param config
     * @param dao
     */
    private void initSysSetting(NutConfig config, Dao dao) {

    }

    /**
     * 初始化Velocity
     *
     * @param config
     * @throws IOException
     */
    private void velocityInit(NutConfig config) throws IOException {
        log.info("Veloctiy Init Start...");
        Properties p = new Properties();
        p.setProperty("resource.loader", "file,classloader");
        p.setProperty("file.resource.loader.path", config.getAppRoot());
        p.setProperty("file", "org.apache.velocity.tools.view.WebappResourceLoader");
        p.setProperty("classloader.resource.loader.class", "com.cyx.nutz.sys.view.VelocityResourceLoader");
        p.setProperty("classloader.resource.loader.path", config.getAppRoot());
        p.setProperty(Velocity.INPUT_ENCODING, "UTF-8");
        p.setProperty(Velocity.OUTPUT_ENCODING, "UTF-8");
        p.setProperty("velocimacro.library.autoreload", "false");
        p.setProperty("classloader.resource.loader.root", config.getAppRoot());
        p.setProperty("velocimarco.library.autoreload", "true");
        p.setProperty("runtime.log.error.stacktrace", "false");
        p.setProperty("runtime.log.warn.stacktrace", "false");
        p.setProperty("runtime.log.info.stacktrace", "false");
        p.setProperty("runtime.log.logsystem.class", "org.apache.velocity.runtime.log.SimpleLog4JLogSystem");
        p.setProperty("runtime.log.logsystem.log4j.category", "velocity_log");
        p.setProperty("velocimacro.library", "/WEB-INF/template/common/globals.html");
        Velocity.init(p);
        log.info("Veloctiy Init End.");
    }

}